package com.swq.java.code.chapter20.code03;

import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;

public class IconsDemo extends JFrame {
    private static Icon[] icons;
    private JButton jb1, jb2 = new JButton("Disable");
    private boolean flag = false;

    private URL getResource(String name) {
        return getClass().getClassLoader().getResource(name);
    }
    public IconsDemo(String title) {
        super(title);
        setLayout(new FlowLayout());

        icons = new Icon[]{
                //  2019/4/29 这里做了点修改 直接取resources里面的资源
                new ImageIcon(getResource("image0.jpg")),
                new ImageIcon(getResource("image1.jpg")),
                new ImageIcon(getResource("image2.jpg")),
                new ImageIcon(getResource("image3.jpg")),
                new ImageIcon(getResource("image4.jpg")),
        };

        jb1 = new JButton("Pet", icons[0]);
        jb1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (flag) {
                    jb1.setIcon(icons[0]);
                    flag = false;
                } else {
                    jb1.setIcon(icons[1]);
                    flag = true;
                }
            }
        });

        jb1.setVerticalAlignment(JButton.TOP);
        jb1.setHorizontalAlignment(JButton.LEFT);

        jb1.setRolloverEnabled(true);
        jb1.setRolloverIcon(icons[2]); //设置鼠标移动到按钮区域的图标
        jb1.setPressedIcon(icons[3]);  //设置按下按钮时的图标。
        jb1.setDisabledIcon(icons[4]); //设置按钮无效状态下的图标。

        jb1.setToolTipText("Click Me!");
        add(jb1);

        jb2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (jb1.isEnabled()) {
                    jb1.setEnabled(false);  //使按钮失效
                    jb2.setText("Enable");
                } else {
                    jb1.setEnabled(true);  //使按钮有效
                    jb2.setText("Disable");
                }
            }
        });
        add(jb2);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        new IconsDemo("Hello");
    }
}